<template>
  <el-form-item
    :class="{ mb0 }"
    :label="label_"
    :prop="name"
    :required="required"
    :ruels="rules"
    v-bind="border"
  >
    <template v-if="$slots.label">
      <slot name="label" :label="label" />
    </template>
    <component :is="tag" :model-value="mv" v-bind="$attrs">
      <template v-if="options_">
        <component
          :is="option.tag"
          v-for="option in options_"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        >
          <template v-if="option.text"> {{ option.text }}</template>
        </component>
      </template>
    </component>
  </el-form-item>
</template>

<script lang="ts" setup>
  import { computed, inject } from 'vue';
  import type { Component } from 'vue';
  import { Field, getDefaultValue, SelectorOptions, SelectorOption } from './form';
  import { getSelectorOptionItemCreator, OptionItem } from './widget/FieldOptionCreators';
  import { getWidget, WidgetName } from './widgets';
  import { formContextKey, FormRules } from 'element-plus';

  const props = defineProps<{
    /**
     * el-form-item 配置
     */
    border?: Record<string, unknown>;
    /**
     * 绑定元数据KEY
     */
    name: string;
    /**
     * 控件名称
     */
    widget: WidgetName;
    /**
     * 如果可以，通过Form的rules参数传递
     */
    rules?: FormRules;
    /**
     * 如果可以，通过Form的rules参数传递
     */
    required?: boolean;
    label?: string;
    translate?: () => undefined;
    options?: SelectorOptions;
    // disoptions?: SelectorOptionsDisable;
    modelValue?: unknown;
  }>();

  // 联系上下文
  const form = inject(formContextKey);
  const label_ = computed<undefined | string>(() =>
    form?.labelWidth === 'none' ? undefined : props.label
  );
  const mb0 = form?.inline;

  const mv = computed(() => {
    return props.modelValue !== undefined
      ? props.modelValue
      : getDefaultValue({
          ...props
        } as Field);
  });

  const tag = computed<Component>(() => {
    return getWidget(props.widget);
  });

  const options_ = computed<false | Array<OptionItem>>(() => {
    const creator = getSelectorOptionItemCreator(props.widget);
    if (!creator || !Array.isArray(props.options)) return false;

    return props.options.map((option: SelectorOption) => {
      return creator(option, { ...props });
      // 执行disable操作
      // if (props.disoptions) item.disabled = props.disoptions[index];
      // return item;
    });
  });
</script>

<style scoped>
  .mb0 {
    margin-bottom: 0;
  }
</style>
